/**
 * Copyright © 2014 Winit Corp. All rights reserved.
 * This software is proprietary to and embodies the confidential
 * technology of Winit Corp.  Possession, use, or copying
 * of this software and media is authorized only pursuant to a
 * valid written license from Winit Corp or an authorized sublicensor.
 */
package com.winit.openapi.fsp.controller;



import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.fsp.spi.payment.GoodPaymentService;
import com.winit.fsp.spi.payment.command.GoodPaymentCommand;
import com.winit.fsp.spi.payment.command.PreGoodPaymentCommand;
import com.winit.fsp.spi.payment.command.QueryGoodPaymentCommand;
import com.winit.fsp.spi.payment.vo.GoodPayment;
import com.winit.fsp.spi.payment.vo.GoodPaymentInfo;
import com.winit.fsp.spi.payment.vo.PreGoodPayment;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * TODO weifeng.liu: Change to the actual description of this class
 * @version   Revision History
 * <pre>
 * Author     Version       Date        Changes
 * weifeng.liu    1.0           2015年4月8日     Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value="/fsp/payment")
public class GoodPaymentController extends BaseController{
    
    @Autowired
    private GoodPaymentService goodPaymentService;

    @RequestMapping(value="/preinfo")
    public String preInfo(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg){
        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            PreGoodPaymentCommand command =new PreGoodPaymentCommand();
            command.setLoanId(json.getLong("loanId"));
            PreGoodPayment payment= goodPaymentService.getReadyInfo(command);
            responseMsg.setData(payment);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    @RequestMapping(value="/goodPaymentInfo")
    public String goodPaymentInfo(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg){
        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            GoodPaymentCommand command =new GoodPaymentCommand();
            command.setLoanId(json.getLong("goodPaymentId"));
            GoodPaymentInfo payment= goodPaymentService.getGoodsPaymentInfo(command);
            responseMsg.setData(payment);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    
    @RequestMapping(value = "/createPayment")
    public String createPayment(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GoodPaymentCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            try {
            command = JSONObject.parseObject(json.toJSONString(), GoodPaymentCommand.class);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING, e.getMessage());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        /*CommandContext ctx = CommandContext.getContext();
        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        command.setPartnerId(bpartner.getcBpartnerId().intValue());*/
        Long id = goodPaymentService.createPayment(command);
        responseMsg.setData(id);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryGoodPayment")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        QueryGoodPaymentCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validpageParams(json);
            command = JSONObject.parseObject(json.toJSONString(), QueryGoodPaymentCommand.class);
            
            Searchable searchable = buildSearchPageParams(json);
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable searchable = buildSearchPageParams(null);
            command = new QueryGoodPaymentCommand();
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        Page<GoodPayment> pagelist = goodPaymentService.query(command);
        
        if (pagelist != null) {

            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pagelist.getPageable().getPageNumber() + 1);
            pageMap.put("pageSize", pagelist.getPageable().getPageSize());
            pageMap.put("totalCount", pagelist.getTotalElements());

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", pagelist.content);
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }
        //responseMsg.setData(list);

        return SUCCESS;
    }

    
    private Searchable buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (json != null && json.containsKey("pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            // pageNo
            if (pageParams.containsKey("pageNo")) {
                pageNo = pageParams.getInteger("pageNo");
            }
            // pageSize
            if (pageParams.containsKey("pageSize")) {
                pageSize = pageParams.getInteger("pageSize");
            }
        }
        Searchable search = Searchable.newSearchable();
        search.setPage(pageNo - 1, pageSize);

        // search.addSort(new Sort(Direction.DESC, "CREATED"));

        return search;
    }
    
    private void validpageParams(JSONObject json) {
        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");

                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");

                if (pageParams.containsKey("pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (pageParams.containsKey("pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }
}
